package com.example.farmeri.ui.news;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.example.farmeri.R;
import com.example.farmeri.data.DataParam;
import com.example.farmeri.pojo.Messages;
import com.example.farmeri.presenter.message.IMessageManagerContract;
import com.example.farmeri.presenter.message.MessageManagerPresenter;
import com.example.farmeri.tools.IdentUtils;
import com.example.farmeri.tools.KeyboardUtils;
import com.example.farmeri.ui.base.BaseLinearRecycleViewActivity;
import com.example.farmeri.adapter.MyItemDecoration;
import com.example.farmeri.ui.login.LoginActivity;
import com.google.android.material.bottomsheet.BottomSheetBehavior;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;

public class NewsManagerActivity extends BaseLinearRecycleViewActivity<MessageManagerPresenter>
    implements IMessageManagerContract {

    @BindView(R.id.news_manager_main)
    ViewGroup mainLayout; //主页面

    @BindView(R.id.news_manager_search)
    ViewGroup searchLayout; //搜索页

    @BindView(R.id.search_cancer)
    TextView searchCancer; //取消搜索

    @BindView(R.id.search_edit)
    EditText searchEdit; //搜索

    @BindView(R.id.search_recycle)
    RecyclerView searchRecycle; //搜索结果

    @BindView(R.id.news_data_recycle_view)
    RecyclerView recyclerView; //搜索结果

    @BindView(R.id.news_manager_swipe)
    SwipeRefreshLayout srl; //刷新

    @BindView(R.id.newsmanager_checkedNum)
    TextView checkedNum; //已勾选消息数

    @BindView(R.id.news_manager_del_multi)
    Button btn_mutil_delete;//消息批量删除按钮

    @BindView(R.id.news_manager_readbutton_multi)
    Button btn_mutil_read;//消息已读按钮


    Integer selectIndex;    //列表中操作控件的位置
    String  selectId;    //列表中操作消息的id
    List<String> temp_num = new ArrayList<>();
    List<String> selectIds = new ArrayList<>();
    NewsManageAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_manager);
        init();
        //批量删除
        btn_mutil_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //从最大的开始删除
                Collections.sort(temp_num);
                for (int i=temp_num.size()-1;i>=0;i--){
                    Log.d("TAG", "onClick: position"+temp_num.get(i));
                    mAdapter.notifyItemRemoved(Integer.parseInt(temp_num.get(i)));
                    present.deleteMessage(selectIds.get(i));
                }
                temp_num = new ArrayList<>();
                selectIds = new ArrayList<>();
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                checkedNum.setText("已勾选"+temp_num.size()+"个");
            }
        });
        // 批量已读
        btn_mutil_read.setOnClickListener((View v)->{
            Collections.sort(temp_num);
            for (int i=temp_num.size()-1;i>=0;i--) {
                NewsManageAdapter.MyViewHolder holder = (NewsManageAdapter.MyViewHolder) recyclerView.findViewHolderForAdapterPosition(Integer.parseInt(temp_num.get(i)));
                holder.img_read.setVisibility(View.GONE);
                present.readMessage(selectIds.get(i));
            }
        });

        //刷新功能
        srl.setOnRefreshListener(() -> {
            initData();
            if (isRefreshFrequently()) {
                showToast("频繁刷新");
//                srl.setRefreshing(false);
                present.reduceCredit(DataParam.getUserInfo().getId());
            }
        });
    }

    long time;
    /**
     * 是否频繁刷新
     * @return
     */
    private boolean isRefreshFrequently() {
        long now = System.currentTimeMillis();
        if (now - time < 5*1000){
            time = now;
            return true;
        }
        time = now;
        return false;
    }

    private void init() {
        ButterKnife.bind(this);
        present = new MessageManagerPresenter(this);
        //设置ToolBar
        initToolBar(R.id.news_manager_toolbar,"查看消息",true);
        //设置底部弹出框
        initBottomBehavior(R.id.newsmanager_bottom_container);
        //设置底部模态框
        initBottomSheetDialog(R.layout.dialog_model); //单条数据操作
        initSingleOperate();
        //初始化搜索页
        initSearchPager();
        //初始化数据
        initData();
    }

    private void initData() {
        SharedPreferences sp = getSharedPreferences(getString(R.string.share_preference_user_info),MODE_PRIVATE);
        String id = sp.getString("id","");
        present.getAllMessages(id,1,999);
    }

    protected void recyclerViewAddData(RecyclerView recyclerView,RecyclerView.Adapter adapter,int orientation,int SpaceHeight) {
        MyItemDecoration decoration = new MyItemDecoration(SpaceHeight);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,orientation,false);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(linearLayoutManager);
//        recyclerView.addItemDecoration(decoration);
    }

    private void initAdapter(Messages messages) {
        mAdapter = new NewsManageAdapter(this,getScreeWidth(),messages);
        linearRecyclerViewAddData(R.id.news_data_recycle_view,
                mAdapter,
                MyItemDecoration.HIGH_LINE);
        //为列表内的控件(锁定、删除等）设置监听
        mAdapter.setonExtraClickListenerNews(new OnExtraClickListenerNews() {
            @Override
            public void onReadClick(View v, int position,String messageId) {
                present.readMessage(messageId);
            }

            @Override
            public void onDelClick(View v, int position,String messageId) {
                bottomSheetDialog.show();
                selectIndex = position;
                selectId = messageId;
            }

            @Override
            public void onChecked(int position,String  messageId) {
                if (temp_num.size() == 0){
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                }
                temp_num.add(String.valueOf(position));
                selectIds.add(messageId);
                checkedNum.setText("已勾选"+temp_num.size()+"个");
            }

            @Override
            public void onUnChecked(int position,String  messageId) {
                temp_num.remove(String.valueOf(position));
                selectIds.remove(messageId);
                checkedNum.setText("已勾选"+temp_num.size()+"个");
                if (temp_num.size() == 0){
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                }
            }
        });
    }

    /**
     * 初始化搜索页面
     */
    private void initSearchPager() {
        //搜索监听
        searchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((actionId == 0 || actionId == 3) && event != null) {
                    linearRecyclerViewAddData(R.id.search_recycle,
                            mAdapter,
                            MyItemDecoration.HIGH_LINE);
                    return true;
                }
                return false;
            }
        });

        //取消搜索
        searchCancer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideSearchLayout();
            }
        });
    }

    private void showSearchLayout(){
        searchLayout.setVisibility(View.VISIBLE);
        mainLayout.setVisibility(View.GONE);
        //searchRecycle.setAdapter();
    }

    private void hideSearchLayout(){
        searchLayout.setVisibility(View.GONE);
        mainLayout.setVisibility(View.VISIBLE);
        searchRecycle.setAdapter(null);
        KeyboardUtils.hideKeyboard(searchEdit);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        String ident = DataParam.getUserInfo().getIdentity();
        if (IdentUtils.hasPower(IdentUtils.IDENT_SEND_MESSAGE)) {
            MenuItem add = menu.add("添加");
            add.setIcon(getDrawable(R.drawable.ic_add));
            add.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
            add.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    Intent intent = new Intent(NewsManagerActivity.this, NewsSendActivity.class);
                    startActivity(intent);
                    return true;
                }
            });
        }

        //搜索
        MenuItem search = menu.add("搜索");
        search.setIcon(getDrawable(R.drawable.ic_search_white_24dp));
        search.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        search.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                showSearchLayout();
                return true;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }

    TextView confirm;   //单选确定
    TextView cancer;    //单选返回
    // 单选删除
    protected void initSingleOperate() {
        TextView hint = dialogView.findViewById(R.id.dialog_bottom_hint);
        hint.setText("确定删除该消息吗");
        //单选删除确定
        confirm = dialogView.findViewById(R.id.dialog_bottom_confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAdapter.notifyItemRemoved(selectIndex);
                bottomSheetDialog.cancel();
                present.deleteMessage(selectId);
            }
        });
        //单选删除取消
        cancer = dialogView.findViewById(R.id.dialog_bottom_cancer);
        cancer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.cancel();
            }
        });
    }

    @Override
    public void onMessageResult(Messages data) {
        srl.setRefreshing(false);
        initAdapter(data);
        recyclerViewAddData(recyclerView,mAdapter, LinearLayoutManager.VERTICAL,MyItemDecoration.MIDDLE_LINE);
    }

    @Override
    public void onMessageError(String message) {
        if (message!=null){
            showMessage(message);
        }
    }

    @Override
    public void onCreditReduceSuccess() {
        if (DataParam.getUserInfo().getCredit()<=0){
            showToast("用户信誉值过低，已被锁定");
            startActivity(new Intent(this, LoginActivity.class));
        }
    }

    @Override
    public void showMessage(String msg) {
        showToast(msg);
    }
}









